//
//  AppDelegate.m
//  ebook
//
//  Created by 吴超飞 on 16/1/14.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "AppDelegate.h"
#import "BaiduMobStat.h"
#import "CatchCrash.h"
#import <TestinDataAnalysis/TestinDataAnalysis.h>
/*
//＝＝＝＝＝＝＝＝＝＝ShareSDK头文件＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
//微信SDK头文件
#import "WXApi.h"
//新浪微博SDK头文件
#import "WeiboSDK.h"
//================  */
#import "AdViewController.h"
#import "UIImageView+WebCache.h"
#import "UIImageView+AFNetworking.h"
#import "DownloadManager.h"
#import "BaiduMobAdSDK/BaiduMobAdSplash.h"
#import "MTRotatingScreen.h"
#import <AVFoundation/AVFoundation.h>
#import "PhoneticReadingManager.h"
//#import <GoogleMobileAds/GoogleMobileAds.h>
#import "GuestLoginManager.h"
#import "LaunchViewController.h"
#import "AdViewManager.h"

@interface AppDelegate()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    //注册消息处理函数的处理方法
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    
    [AdViewManager showAdOnController:[UIApplication sharedApplication].delegate.window.rootViewController isFromBackgroud:NO];
    
//百度统计  使用BaiduMobStatCodeless集成后可以跳过该步骤，只需要配置info.plist中的参数即可
//    [[BaiduMobStat defaultStat] startWithAppId:kBaiduMobStatAppKey];
    
//     Initialize Google Mobile Ads SDK
//    [FIRApp configure];
//    [GADMobileAds configureWithApplicationID:kGoogleAdMobAppid];
    
    //报错统计
    [self initTestinBugoutWithOptions:launchOptions];
    
    //分享
    [self share];
    
    [self initSession];
    
    if (iOS11) {//全局适配contentInsetAdjustmentBehavior属性
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    
//    UINavigationController *nav = [[UINavigationController alloc]init];
//    LaunchViewController *vc = [[LaunchViewController alloc] init];
//    [nav addChildViewController:vc];
//    [vc.navigationController setNavigationBarHidden:YES];
//    
//    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//    self.window.backgroundColor = [UIColor whiteColor];
//    self.window.rootViewController = nav;
//    [self.window makeKeyAndVisible];
    
    return YES;
}

-(void)initTestinBugoutWithOptions:(NSDictionary *)launchOptions {
    
    TestinDataConfig * config = [TestinDataConfig shareConfig];
    config.enabledShakeFeedback = YES;//开启反馈问题的功能
    config.enabledMonitorException = YES;//开启异常监视器
    config.enableSysLog = NO;
    config.crashScreenshot = YES;
    config.enabledShakeFeedback = YES;
    config.printBugOutLog = YES;
    [TestinDataAnalysis initWithProjectId:kTestinDataAnalysisAppKey WithConfig:config launchOptions:launchOptions];
}

- (void)initSession {
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    
    NSError *error;
    if (![session setCategory:AVAudioSessionCategoryPlayback error:&error]) {
        MTLog(@"Category Error: %@", [error localizedDescription]);
    }
    
    if (![session setActive:NO error:&error]) {
        MTLog(@"Activation Error: %@", [error localizedDescription]);
    }
}

- (void)share {
    /*
    [ShareSDK registerApp:KShareAppKey
          activePlatforms:@[
                            @(SSDKPlatformTypeWechat),
                            @(SSDKPlatformTypeQQ),
                            @(SSDKPlatformTypeSinaWeibo)
                            ]
                 onImport:^(SSDKPlatformType platformType) {
                     
                     switch (platformType)
                     {
                         case SSDKPlatformTypeWechat:
                             [ShareSDKConnector connectWeChat:[WXApi class] delegate:self];
                             break;
                         case SSDKPlatformTypeSinaWeibo:
                             [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                             break;
                         case SSDKPlatformTypeQQ:
                             [ShareSDKConnector connectQQ:[QQApiInterface class]
                                        tencentOAuthClass:[TencentOAuth class]];
                             break;
                         default:
                             break;
                     }
                 }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
              
              switch (platformType)
              {
                  case SSDKPlatformTypeWechat:
                      [appInfo SSDKSetupWeChatByAppId:kWechatAppid
                                            appSecret:kWechatAppscret];
                      break;
                  case SSDKPlatformTypeQQ:
                      [appInfo SSDKSetupQQByAppId:kQQAppid
                                           appKey:KQQAppkey
                                         authType:SSDKAuthTypeBoth];
                      break;
                  case SSDKPlatformTypeSinaWeibo:
                      [appInfo SSDKSetupSinaWeiboByAppKey:kSinaAppkey
                                                appSecret:KSinaAppSecret
                                              redirectUri:KSinaRedirectUri
                                                 authType:SSDKAuthTypeBoth];
                      break;
                  default:
                      break;
              }
          }];*/
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    
    return UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskLandscapeRight;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    if (![PhoneticReadingManager shareManager].isPlaying) [self endRemoteControl];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    if (![PhoneticReadingManager shareManager].isPlaying) [self endRemoteControl];
    [[NSUserDefaults standardUserDefaults] setDouble:[[NSDate date] timeIntervalSince1970] forKey:kLastEnterBackgroundTime];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

//结束远程控制
- (void)endRemoteControl {
    
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    
    [self resignFirstResponder];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    if([AdViewManager isNeedShowAdWhenEnterforground]){
        
        AdViewController *advc = [[AdViewController alloc] initIsFromBackground:YES];
        [[AdViewManager getCurrentVC] presentViewController:advc animated:NO completion:nil];
    }
    
    if([AdViewManager isOverTime:6*60*60]){//进入后台时间超过6小时，需重新自动登录一次
        [GuestLoginManager autoLogin:^(BOOL issuc) {
        }];
    }
    
    StatSDK *ss = [[StatSDK alloc] init];
    [ss stat];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    //    [UMSocialSnsService applicationDidBecomeActive];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    MTLog(@"applicationWillTerminate");
}

//#pragma mark - 用户通知(推送) _自定义方法
//
///** 注册用户通知 */
//- (void)registerUserNotification {
//
//    /*
//     注册通知(推送)
//     申请App需要接受来自服务商提供推送消息
//     */
//
//    // 判读系统版本是否是“iOS 8.0”以上
//    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ||
//        [UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
//
//        // 定义用户通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
//        UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
//
//        // 定义用户通知设置
//        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
//
//        // 注册用户通知 - 根据用户通知设置
//        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
//    } else { // iOS8.0 以前远程推送设置方式
//        // 定义远程通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
//        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
//
//        // 注册远程通知 -根据远程通知类型
//        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
//    }
//}
//
//#pragma mark - 用户通知(推送)回调 _IOS 8.0以上使用
//
///** 已登记用户通知 */
//- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
//    // 注册远程通知（推送）
//    [application registerForRemoteNotifications];
//}
//
//#pragma mark - 远程通知(推送)回调
//
///** 远程通知注册成功委托 */
//- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
//    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
//    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
//    MTLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
//
//    // [3]:向个推服务器注册deviceToken
//    [GeTuiSdk registerDeviceToken:token];
//}
//
///** 远程通知注册失败委托 */
//- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
//    MTLog(@"\n>>>[DeviceToken Error]:%@\n\n", error.description);
//}
//
//#pragma mark - APP运行中接收到通知(推送)处理
//
///** APP已经接收到“远程”通知(推送) - (App运行在后台/App运行在前台) */
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
//    application.applicationIconBadgeNumber = 0; // 标签
//
//    MTLog(@"\n>>>[Receive RemoteNotification]:%@\n\n", userInfo);
//}
//
///** APP已经接收到“远程”通知(推送) - 透传推送消息  */
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
//
//    // 处理APN
//    MTLog(@"\n>>>[Receive RemoteNotification - Background Fetch]:%@\n\n", userInfo);
//
//    completionHandler(UIBackgroundFetchResultNewData);
//}
//
//#pragma mark - GeTuiSdkDelegate
//
///** SDK启动成功返回cid */
//- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
//    // [4-EXT-1]: 个推SDK已注册，返回clientId
//    MTLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
//    [[NSUserDefaults standardUserDefaults] setObject:clientId?clientId:@"" forKey:KPushClientId];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//}
//
///** SDK遇到错误回调 */
//- (void)GeTuiSdkDidOccurError:(NSError *)error {
//    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
//    MTLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
//}
//
//
///** SDK收到透传消息回调 */
//- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
//
//    // [4]: 收到个推消息
//    NSString *payloadMsg = nil;
//    if (payloadData) {
//        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
//    }
//
//    NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@", taskId, msgId, payloadMsg, offLine ? @"<离线消息>" : @""];
//    MTLog(@"\n>>>[GexinSdk ReceivePayload]:%@\n\n", msg);
//}
//
///** SDK收到sendMessage消息回调 */
//- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
//    // [4-EXT]:发送上行消息结果反馈
//    NSString *msg = [NSString stringWithFormat:@"sendmessage=%@,result=%d", messageId, result];
//    MTLog(@"\n>>>[GexinSdk DidSendMessage]:%@\n\n", msg);
//}
//
///** SDK运行状态通知 */
//- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
//    // [EXT]:通知SDK运行状态
//    MTLog(@"\n>>>[GexinSdk SdkState]:%u\n\n", aStatus);
//}
//
///** SDK设置推送模式回调 */
//- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
//    if (error) {
//        MTLog(@"\n>>>[GexinSdk SetModeOff Error]:%@\n\n", [error localizedDescription]);
//        return;
//    }
//
//    MTLog(@"\n>>>[GexinSdk SetModeOff]:%@\n\n", isModeOff ? @"开启" : @"关闭");
//}

@end
